//
//  RASecondsCountViewController.m
//  RACExample
//
//  Created by 山刘 on 2020/6/24.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "RASecondsCountViewController.h"
#pragma mark - ====================VM层====================
@interface RASecondsCountViewModel : NSObject
@property (nonatomic, strong) RACCommand *requestCommand;
@property (nonatomic, strong) RACSignal *requestSignal;

@property (nonatomic, assign) BOOL buttonEnabled;
@property (nonatomic, copy) NSString *countStirng;
@property (nonatomic, assign) NSInteger countTotal;
@property (nonatomic, strong) RACSignal *subject;
@end

@implementation RASecondsCountViewModel
#pragma mark - Init
-(instancetype)init{
    if (self = [super init]) {
        self.countStirng = @"获取验证码";
        self.buttonEnabled = YES;
        self.countTotal = 5;
        [self racInit];
    }
    return self;
}

-(void)secondsCount {
    [[[[[[RACSubject interval:1 onScheduler:[RACScheduler mainThreadScheduler]] startWith:[NSDate date]] scanWithStart:@(self.countTotal) reduce:^id _Nullable(NSNumber*  _Nullable running, NSDate * _Nullable next) {
        return @( running.integerValue - 1);
    }] takeUntilBlock:^BOOL(NSNumber*  _Nullable x) {
        return x.integerValue < 0;
    }] map:^id _Nullable(id  _Nullable value) {
        return  [NSString  stringWithFormat:@"%@s可重发",value];
    }] subscribeNext:^(id  _Nullable x) {
        self.countStirng = x;
        self.buttonEnabled = NO;
    }completed:^{
        self.countStirng = @"重新发送";
        self.buttonEnabled = YES;
    }];
}

- (void)racInit {
    @weakify(self);
    _subject = [[[[RACSubject interval:1 onScheduler:[RACScheduler mainThreadScheduler]] startWith:[NSDate date]] scanWithStart:@(5) reduce:^id _Nullable(NSNumber*  _Nullable running, NSDate * _Nullable next) {
        NSLog(@"RACSubject running = %@",running);
        return @( running.integerValue - 1);
    }] takeUntilBlock:^BOOL(NSNumber*  _Nullable x) {
        return x.integerValue<0;
    }];
    
      _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
          return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
              @strongify(self);

              // Code here...
              [self secondsCount];
              
              // 其他业务逻辑，网络请求...
              [subscriber sendCompleted];

              return [RACDisposable disposableWithBlock:^{
              }];
          }];
      }];
}
@end

#pragma mark - ====================V层====================

@interface RASecondsCountViewController ()
@property (weak, nonatomic) IBOutlet UIButton *countButton;
@property(nonatomic, strong) RASecondsCountViewModel *viewModel;
@end

@implementation RASecondsCountViewController
-(RASecondsCountViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[RASecondsCountViewModel alloc]init];
    }
    return _viewModel;
}

- (void )viewDidLoad {
    [super viewDidLoad];
    //    [self testOne];
    //    [self.viewModel.requestCommand execute:nil];
    //    self.countButton.rac_command = self.viewModel.requestCommand;
    
    [[self.countButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.viewModel.requestCommand execute:nil];
    }];
    [RACObserve(self.viewModel, countStirng) subscribeNext:^(id  _Nullable x) {
        self.countButton.titleLabel.text = x;
        [self.countButton setTitle:x forState:UIControlStateNormal];
    }];
    [RACObserve(self.viewModel, buttonEnabled) subscribeNext:^(NSNumber*  _Nullable x) {
        self.countButton.enabled = [x boolValue];
    }];
    //    [[self.viewModel.requestSignal map:^id _Nullable(id  _Nullable value) {
    //        return [NSString  stringWithFormat:@"剩余%@",value];
    //    }] subscribeNext:^(id  _Nullable x) {
    //        NSLog(@"running = %@",x);
    //    }];
}

-(void )testOne{
    UIButton  *  btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"按钮" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor colorWithRed:58/255.0f green:157/255.0f blue:255/255.0f alpha:1.0f]];
    btn.frame=  CGRectMake(30,100,100,30);
    btn.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    btn.layer.cornerRadius = 6;
    btn.layer.masksToBounds = YES;
    [self.view addSubview:btn];
    RACSignal *  (^countBlock)(UIButton * ) = ^RACSignal * (UIButton *  btn){
        RACSignal *  countsingal =  [[[[RACSignal interval:1
                                               onScheduler:[RACScheduler mainThreadScheduler]]
                                       startWith:[NSDate date]]
                                      scanWithStart:@(10)reduce:^id (NSNumber * running,id next) {
            NSLog(@"running = %@",running);
            return @(running.integerValue-1);
        }]takeUntilBlock:^BOOL(NSNumber * x) {
            return x.integerValue<0;
        }];
        return countsingal;
    };
    
    RACSignal *  (^CountBlock)(UIButton * ) = ^RACSignal * (UIButton *  btn){
        RACSignal *  timeSigal =  [countBlock(btn) map:^id (NSNumber *  value) {
            return  [NSString  stringWithFormat:@"剩余%@",value];
        }];
        btn.enabled=NO;
        [btn setBackgroundColor:[UIColor grayColor]];
        __block id  saveSubscriber =nil;
        RACSignal * resetStringSignal =
        [RACSignal createSignal:^RACDisposable  * (id <RACSubscriber>  subscriber) {
            saveSubscriber = subscriber;
            return nil;
        }];
        
        [timeSigal subscribeCompleted:^{
            btn.enabled=YES;
            [btn setBackgroundColor:[UIColor colorWithRed:58/255.0f green:157/255.0f blue:255/255.0f alpha:1.0f]];
            [saveSubscriber sendNext:@"按钮"];
            [saveSubscriber sendCompleted];
            NSLog(@"timer singal complte");
        }];
        [btn rac_liftSelector:@selector(setTitle:forState:)
                  withSignals:[RACSignal merge:@[timeSigal,resetStringSignal]],
         [RACSignal return :@(UIControlStateNormal)], nil];
        return timeSigal;
    };
    btn. rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal  * (id  input) {
        return CountBlock(btn);
    }];
}
@end
